
from trade.IBExchange import Exchange
from broker.tws.constant.Constant import *
from data.model.Params import *

accountId = "DU2082325"
port = 5000
exchange = Exchange(accountId, port)


def get_accinfo():

    power = total_assets = cash = market_val = frozen_cash = avl_withdrawal_cash = 0
    # 账户资金数据
    ret, summary = exchange.GetAccountSummary()
    if ret.code == RetCode.OK:
        # 分别是：购买力，资产净值，现金，证券市值，冻结金额，风控状态，可提金额
        total_assets = summary.fullavailablefunds
        cash = summary.availablefunds
        power = summary.buyingpower

    ret, ledger = exchange.GetAccountLedger()
    if ret.code == RetCode.OK:
        market_val = ledger.stockmarketvalue
        frozen_cash = ledger.settledcash
        avl_withdrawal_cash = ledger.cashbalance
        # 分别是：持仓方向，市值，今日盈亏金额
        today_pl_val = ledger.unrealizedpnl

    # symbol = "US.TSLA"
    # price = 1000.00
    # side = Side.BUY
    # quantity = 100
    # orderReq = OrderReq.stock(symbol, price, side, quantity)
    # ret, preorder = exchange.PreviewOrders(orderReq)
    # if ret.code == RetCode.OK:
    #     # 分别是：购买力，资产净值，现金，证券市值，冻结金额，风控状态，可提金额
    #     power = preorder.marginLevel * total_assets


    if ret_code == RET_OK:
        # 分别是：购买力，资产净值，现金，证券市值，冻结金额，风控状态，可提金额
        ret_data = ret_data.fillna(0)
        ret_data = ret_data[['power', 'total_assets', 'cash', 'market_val',
                             'frozen_cash', 'risk_level', 'avl_withdrawal_cash']].to_dict(orient='records')[0]
        # print(ret_data)

        power = ret_data['power']
        total_assets = ret_data['total_assets']
        cash = ret_data['cash']
        market_val = ret_data['market_val']
        frozen_cash = ret_data['frozen_cash']
        risk_level = ret_data['risk_level']
        avl_withdrawal_cash = ret_data['avl_withdrawal_cash']

    # 账户持仓列表
    ret_code, ret_data = trd_ctx.position_list_query('', None, None, TrdEnv)
    long_market_val = short_market_val = today_pl_val = 0
    if ret_code == RET_OK:
        # 分别是：持仓方向，市值，今日盈亏金额
        ret_data = ret_data[['position_side', 'market_val', 'today_pl_val']].to_dict(orient='records')
        if ret_data != []:
            long_market_val = round(sum([x['market_val'] for x in ret_data if x['position_side'] == 'LONG']), 2)
            short_market_val = round(sum([x['market_val'] for x in ret_data if x['position_side'] == 'SHORT']), 2)
            today_pl_val = round(sum([x['today_pl_val'] if x['today_pl_val']!='N/A' else 0 for x in ret_data]), 2)
    return {'class': name, 'acc_id': acc_id, 'power': power, 'total_assets': total_assets, 'cash': cash,
            'market_val': market_val,
            'frozen_cash': frozen_cash, 'avl_withdrawal_cash': avl_withdrawal_cash, 'long_market_val': long_market_val,
            'short_market_val': short_market_val, 'today_pl_val': today_pl_val}

print(get_accinfo('', 'SIMULATE', '', '港股'))




